package cn.com.zero.common.auth.security.handler;

import cn.com.zero.api.auth.constant.HttpHeaderConstants;
import cn.com.zero.base.vo.ResponseVO;
import cn.com.zero.common.auth.constant.SecurityConstants;
import cn.com.zero.common.auth.security.po.AuthUserPO;
import cn.com.zero.common.auth.security.service.AbstractLoginAuthenticationService;
import cn.com.zero.common.auth.security.vo.LoginUserInfoVO;
import cn.com.zero.common.auth.security.vo.UserDetailsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xiongxj
 * @version 1.0.0
 * @Description 自定义的认证成功后的处理类
 * @createTime 2023/3/23 13:23
 */
@Component
public class LoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private AbstractLoginAuthenticationService loginAuthenticationService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetailsVO userDetailsVO = (UserDetailsVO) authentication.getPrincipal();
        AuthUserPO authUser = userDetailsVO.getUserInfo();
        // 获取当前认证用户的登录设备
        String loginDevice = request.getHeader(HttpHeaderConstants.LOGIN_DEVICE_HEADER);

        // 保存用户的登录信息，组装 给前端返回登录成功的用户信息
        LoginUserInfoVO loginUserInfoVO = loginAuthenticationService.saveLoginUser(authUser, loginDevice);

        ResponseVO responseVO = ResponseVO.success(loginUserInfoVO);
        request.setAttribute("loginSuccessResponse", responseVO);
        // 重定向到此路径，由此接口 负责返回给前端 登录成功的信息
        request.getRequestDispatcher(SecurityConstants.SECURITY_CONTROLLER_PATH + "/loginAuthenticationSuccessHandler").forward(request, response);
    }

    @Autowired
    public void setLoginAuthenticationService(AbstractLoginAuthenticationService loginAuthenticationService) {
        this.loginAuthenticationService = loginAuthenticationService;
    }
}
